import { useState, useEffect } from 'react';
import { Table, Button, Space, message, Modal, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, DisconnectOutlined } from '@ant-design/icons';
import { listUsers, deleteUser, createUser, updateUser, kickUser, type User } from '../api/users';
import { UserModal } from '../components/UserModal';

export const Users = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);

  useEffect(() => {
    loadUsers();
  }, []);

  const loadUsers = async () => {
    setLoading(true);
    try {
      const data: any = await listUsers();
      setUsers(data.users || []);
    } catch (error) {
      message.error('Failed to load users');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingUser(null);
    setModalVisible(true);
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setModalVisible(true);
  };

  const handleDelete = (user: User) => {
    Modal.confirm({
      title: 'Confirm Delete',
      content: `Are you sure you want to delete user "${user.username}"?`,
      onOk: async () => {
        try {
          await deleteUser(user.id);
          message.success('User deleted successfully');
          loadUsers();
        } catch (error) {
          message.error('Failed to delete user');
        }
      },
    });
  };

  const handleKick = async (user: User) => {
    try {
      await kickUser(user.id);
      message.success('User kicked successfully');
    } catch (error) {
      message.error('Failed to kick user');
    }
  };

  const handleModalOk = async (values: any) => {
    try {
      if (editingUser) {
        await updateUser(editingUser.id, values);
        message.success('User updated successfully');
      } else {
        await createUser(values);
        message.success('User created successfully');
      }
      setModalVisible(false);
      loadUsers();
    } catch (error) {
      message.error('Operation failed');
    }
  };

  const formatBytes = (bytes: number) => {
    if (!bytes) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 60 },
    { title: 'Username', dataIndex: 'username', key: 'username' },
    {
      title: 'Upload Limit',
      dataIndex: 'max_bandwidth_up',
      key: 'max_bandwidth_up',
      render: (val: number) => val ? `${val / 1024 / 1024} Mbps` : 'Unlimited',
    },
    {
      title: 'Download Limit',
      dataIndex: 'max_bandwidth_down',
      key: 'max_bandwidth_down',
      render: (val: number) => val ? `${val / 1024 / 1024} Mbps` : 'Unlimited',
    },
    {
      title: 'Traffic Used',
      dataIndex: 'traffic_used',
      key: 'traffic_used',
      render: (val: number) => formatBytes(val),
    },
    {
      title: 'Status',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (val: boolean) => (
        <Tag color={val ? 'green' : 'red'}>{val ? 'Enabled' : 'Disabled'}</Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'action',
      width: 180,
      render: (_: any, record: User) => (
        <Space>
          <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)} />
          <Button icon={<DisconnectOutlined />} size="small" onClick={() => handleKick(record)} />
          <Button icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record)} />
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
        <h1 style={{ fontSize: '24px' }}>User Management</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          Add User
        </Button>
      </div>
      <Table dataSource={users} columns={columns} loading={loading} rowKey="id" />
      <UserModal
        visible={modalVisible}
        user={editingUser}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
      />
    </div>
  );
};
